#!groovy

@Library('jenkinslib@master') _

// 调用共享库方法
def tools = new org.devops.tools()
def build = new org.devops.build()      
def depoly = new org.devops.deploy()    
def gitlab =  new org.devops.gitlab()  
def toemail = new org.devops.toemail()
def sonar = new org.devops.sonarqube()
def sonarapi = new org.devops.sonarapi()
def nexus3 = new org.devops.nexus()
def artifactory = new org.devops.artifactory() 

def runOpts			// 初始化一个变量，手动构建时候不会报错


// 用流水线参数赋值到变量
String buildType = "${env.buildType}"
String buildShell = "${env.buildShell}"
String deployHosts = "${env.deployHosts}"

String srcUrl = "${env.srcUrl}"
String branchName = "${env.branchName}"
String artifactUrl = "${env.artifactUrl}"


//配置gitlab提交触发流水线
if ("${runOpts}" == "GitlabPush") {
	branchName = branch - "refs/heads/"

    currentBuild.description = "Trigger by ${userName} ${branch}"
    gitlab.ChangeCommitStatus(projectId,commitSha,"running")   //修改gitlab显示commit构建状态
} else {
	userEmail = "76439984@qq.com"
}

pipeline{
	agent {node {label "master"}}

	stages{
		stage("checkOut"){
			steps{
				script{
					tools.PrintMes("拉取代码","green")
					println("${branchName}")

					checkout([$class: 'GitSCM', 
						branches: [[name: "${branchName}"]], 
						doGenerateSubmoduleConfigurations: false, 
						extensions: [], 
						submoduleCfg: [], 
						userRemoteConfigs: [[credentialsId: 'gitlab-passowd', url: "${srcUrl}"]]])
				}
			}
		}

		stage("Build"){
			steps{
				script{
					tools.PrintMes("构建代码","green")
					//build.Build(buildType,buildShell)
                    artifactory.main(buildType,buildShell)
                    artifactory.PushArtifact()

					//上传制品
					//nexus3.main("maven")

					//发布制品
					//sh "wget ${artifactUrl} && ls"
				}
			}
		}

		stage("QA"){
			steps{
				script{
					//指定sonar是扫描规则
					tools.PrintMes("搜索项目","green")
					reslut = sonarapi.SerarchProject("${JOB_NAME}")
					println(reslut)

					if ("${reslut}" == "false") {
						println("${JOB_NAME}----项目不存在,准备创建项目---->${JOB_NAME}")
						sonarapi.CreateProject("${JOB_NAME}")
					} else {
						println("${JOB_NAME}----项目存在")
					}

					tools.PrintMes("配置项目质量规则","green")
					qpName="${JOB_NAME}".split("-")[0]    //demo-maven-service_dev.split("-")[0] 
														  // 默认策略Sonar%20way
					sonarapi.ConfigQualityProfiles("${JOB_NAME}","java","${qpName}")

					tools.PrintMes("配置项目质量阈","green")
					sonarapi.ConfigQualityGates("${JOB_NAME}","${qpName}")

					//扫描代码
					tools.PrintMes("扫描代码","green")
					sonar.SonarScan("test","${JOB_NAME}","${JOB_NAME}","src")  //指定test环境的sonar调用				
					
					tools.PrintMes("获取扫描结果","green")
					sleep 30   //等30再获取状态
					reslut=sonarapi.GetProjectStatus("${JOB_NAME}")
					println(reslut)

					// 判断值是否有告警
					if (reslut.toString().contains("ERROR")) {
						toemail.Email("代码质量阈错误","${userEmail}") 
						error "代码质量阈错误"    // 终止流水线并报错						
					} else {
						println(reslut)
					}
				}
			}
		}
	}

	post{
		always{
			script{
				println("always")
			}
		}

		success{
			script{
				println("success")
				if ("${runOpts}" == "GitlabPush") {
					gitlab.ChangeCommitStatus(projectId,commitSha,"success")
				}
				toemail.Email("构建成功","${userEmail}")    // 构建成功发邮件
			}
		}

		failure{
            script{
                println("failure")
                if ("${runOpts}" == "GitlabPush") {
                	gitlab.ChangeCommitStatus(projectId,commitSha,"failed")
                }
                toemail.Email("构建失败","${userEmail}")
            }			
		}

        aborted{
            script{
                println("aborted")
                if ("${runOpts}" == "GitlabPush") {
                	gitlab.ChangeCommitStatus(projectId,commitSha,"canceled")
                }
                toemail.Email("构建取消","${userEmail}")
            }
            
        }
	}
}